"""
字典导入导出对话框
"""

import logging
import os
from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QComboBox, QPushButton,
    QProgressBar, QMessageBox, QFileDialog, QTextEdit, QGroupBox
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal

from src.app.modules.dictionary.import_export import DictionaryImportExport

logger = logging.getLogger(__name__)

class ImportExportWorker(QThread):
    """导入导出工作线程"""
    
    progress_updated = pyqtSignal(int, str)
    finished = pyqtSignal(dict)
    
    def __init__(self, operation, dict_type, file_path=None, data=None):
        super().__init__()
        self.operation = operation
        self.dict_type = dict_type
        self.file_path = file_path
        self.data = data
        self.import_export = DictionaryImportExport()
    
    def run(self):
        try:
            if self.operation == 'export':
                self.progress_updated.emit(10, "准备导出数据...")
                
                if self.dict_type:
                    result = self.import_export.export_to_excel(self.dict_type, self.file_path)
                else:
                    result = self.import_export.export_to_excel(file_path=self.file_path)
                
                self.progress_updated.emit(100, "导出完成")
                self.finished.emit(result)
                
            elif self.operation == 'import':
                self.progress_updated.emit(10, "准备导入数据...")
                result = self.import_export.import_from_excel(self.file_path)
                self.progress_updated.emit(100, "导入完成")
                self.finished.emit(result)
                
            elif self.operation == 'export_json':
                self.progress_updated.emit(10, "准备导出JSON数据...")
                result = self.import_export.export_to_json(self.dict_type, self.file_path)
                self.progress_updated.emit(100, "导出完成")
                self.finished.emit(result)
                
            elif self.operation == 'import_json':
                self.progress_updated.emit(10, "准备导入JSON数据...")
                result = self.import_export.import_from_json(self.file_path)
                self.progress_updated.emit(100, "导入完成")
                self.finished.emit(result)
                
        except Exception as e:
            logger.error(f"导入导出操作失败: {e}")
            self.finished.emit({
                'success': False,
                'message': f'操作失败: {str(e)}'
            })

class ImportExportDialog(QDialog):
    """导入导出对话框"""
    
    def __init__(self, operation, dict_type=None, parent=None):
        super().__init__(parent)
        
        self.operation = operation
        self.dict_type = dict_type
        self.worker = None
        
        self.setup_ui()
    
    def setup_ui(self):
        """设置用户界面"""
        is_export = self.operation.startswith('export')
        
        self.setWindowTitle("数据导出" if is_export else "数据导入")
        self.setFixedSize(500, 350)
        self.setModal(True)
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)
        
        # 操作类型
        type_group = QGroupBox("操作设置")
        type_layout = QVBoxLayout(type_group)
        
        # 格式选择
        format_layout = QHBoxLayout()
        format_layout.addWidget(QLabel("数据格式:"))
        
        self.format_combo = QComboBox()
        if is_export:
            self.format_combo.addItems(["Excel", "JSON"])
        else:
            self.format_combo.addItems(["Excel", "JSON"])
        format_layout.addWidget(self.format_combo)
        format_layout.addStretch()
        
        type_layout.addLayout(format_layout)
        
        # 文件路径
        file_layout = QHBoxLayout()
        file_layout.addWidget(QLabel("文件路径:"))
        
        self.file_path_edit = QLineEdit()
        self.file_path_edit.setReadOnly(True)
        file_layout.addWidget(self.file_path_edit)
        
        self.browse_btn = QPushButton("浏览...")
        self.browse_btn.clicked.connect(self.browse_file)
        file_layout.addWidget(self.browse_btn)
        
        type_layout.addLayout(file_layout)
        
        # 字典类型（仅导入时显示）
        if not is_export and not self.dict_type:
            dict_layout = QHBoxLayout()
            dict_layout.addWidget(QLabel("字典类型:"))
            
            self.dict_type_combo = QComboBox()
            dict_layout.addWidget(self.dict_type_combo)
            dict_layout.addStretch()
            
            type_layout.addLayout(dict_layout)
        
        layout.addWidget(type_group)
        
        # 进度条
        progress_group = QGroupBox("操作进度")
        progress_layout = QVBoxLayout(progress_group)
        
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        progress_layout.addWidget(self.progress_bar)
        
        self.status_label = QLabel("准备就绪")
        progress_layout.addWidget(self.status_label)
        
        # 结果显示
        self.result_text = QTextEdit()
        self.result_text.setMaximumHeight(100)
        self.result_text.setVisible(False)
        progress_layout.addWidget(self.result_text)
        
        layout.addWidget(progress_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        self.cancel_btn = QPushButton("取消")
        self.cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_btn)
        
        self.execute_btn = QPushButton("执行" if is_export else "导入")
        self.execute_btn.clicked.connect(self.execute_operation)
        button_layout.addWidget(self.execute_btn)
        
        layout.addLayout(button_layout)
        
        # 加载字典类型
        if not is_export and not self.dict_type:
            self.load_dict_types()
    
    def load_dict_types(self):
        """加载字典类型"""
        try:
            from src.app.modules.dictionary.service import DictionaryService
            service = DictionaryService()
            types = service.get_all_types()
            self.dict_type_combo.addItems(types)
        except Exception as e:
            logger.error(f"加载字典类型失败: {e}")
    
    def browse_file(self):
        """浏览文件"""
        is_export = self.operation.startswith('export')
        file_format = self.format_combo.currentText().lower()
        
        if is_export:
            # 导出文件对话框
            if file_format == 'excel':
                file_filter = "Excel文件 (*.xlsx);;所有文件 (*.*)"
                default_name = f"dictionary_export.{self.dict_type or 'all'}.xlsx"
            else:
                file_filter = "JSON文件 (*.json);;所有文件 (*.*)"
                default_name = f"dictionary_export.{self.dict_type or 'all'}.json"
            
            file_path, _ = QFileDialog.getSaveFileName(
                self, "选择导出文件", default_name, file_filter
            )
        else:
            # 导入文件对话框
            if file_format == 'excel':
                file_filter = "Excel文件 (*.xlsx);;所有文件 (*.*)"
            else:
                file_filter = "JSON文件 (*.json);;所有文件 (*.*)"
            
            file_path, _ = QFileDialog.getOpenFileName(
                self, "选择导入文件", "", file_filter
            )
        
        if file_path:
            self.file_path_edit.setText(file_path)
    
    def execute_operation(self):
        """执行操作"""
        file_path = self.file_path_edit.text().strip()
        if not file_path:
            QMessageBox.warning(self, "警告", "请选择文件路径")
            return
        
        # 检查文件是否存在（导入时）
        if not self.operation.startswith('export') and not os.path.exists(file_path):
            QMessageBox.warning(self, "警告", "文件不存在")
            return
        
        # 禁用按钮
        self.execute_btn.setEnabled(False)
        self.browse_btn.setEnabled(False)
        
        # 显示进度
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        self.status_label.setText("正在处理...")
        
        # 创建工作线程
        operation_map = {
            'export': 'export',
            'import': 'import',
            'export_json': 'export_json',
            'import_json': 'import_json'
        }
        
        dict_type = self.dict_type
        if not dict_type and hasattr(self, 'dict_type_combo'):
            dict_type = self.dict_type_combo.currentText()
        
        self.worker = ImportExportWorker(
            operation_map[self.operation], dict_type, file_path
        )
        
        self.worker.progress_updated.connect(self.on_progress_updated)
        self.worker.finished.connect(self.on_operation_finished)
        
        self.worker.start()
    
    def on_progress_updated(self, value, message):
        """进度更新"""
        self.progress_bar.setValue(value)
        self.status_label.setText(message)
    
    def on_operation_finished(self, result):
        """操作完成"""
        # 恢复按钮
        self.execute_btn.setEnabled(True)
        self.browse_btn.setEnabled(True)
        
        if result['success']:
            self.status_label.setText("操作完成")
            self.result_text.setVisible(True)
            self.result_text.setText(result['message'])
            
            QMessageBox.information(self, "成功", result['message'])
            
            if self.operation.startswith('import'):
                self.accept()  # 导入成功后关闭对话框
        else:
            self.status_label.setText("操作失败")
            self.result_text.setVisible(True)
            self.result_text.setText(result['message'])
            
            QMessageBox.critical(self, "失败", result['message'])
    
    def closeEvent(self, event):
        """关闭事件"""
        if self.worker and self.worker.isRunning():
            self.worker.terminate()
            self.worker.wait()
        event.accept()